import Process, Configuration,os,time, sys,math
from threading import Timer
from Configuration import Configuration

from Performance import Performance
"""
I didn't use rondje as the ai to test the performance of single Ai as it doesn't build
anything in the first year
"""
commands = ["OtviAI","AdmiralAI","Convoy","Rondje","PathZilla", "choochoo", "\"Denver & Rio Grande\"", 
             "PAXLink"]
def setAI(num):
    file = open(game_start_scr_path, "w")
    for i in xrange(0, num/1):
        print >> file, "start_ai " + commands[i]  
    file.close()  

minMap = 6
maxMap = 11
totalTurns = 10

game_start_scr_path = ""
if sys.platform == "win32":
    game_start_scr_path = "c:\\cygwin\\home\\Q\\OpenTTD\\scripts\\game_start.scr"
elif sys.platform.find("linux") >=0 :
    game_start_scr_path = "/home/sq/software/openttd-1.0.4/bin/scripts/game_start.scr"

path = os.path.join("..","test_result")
if os.path.exists(path) == False:
    os.mkdir(path)
path = os.path.join(path, "1a3")
if os.path.exists(path) == False:
    os.mkdir(path)
measurement = Performance()
measurement.flag = 1
measurement.start()
Configuration.set("difficulty", "max_no_competitors", 1)
setAI(1)
for turn in xrange(1, totalTurns + 1/1):
    filename = os.path.join(path ,"test1a3_result_"+"%d"%turn+".txt")
    file = open(filename,"w")
    print >> file, maxMap - minMap + 1
    for i in xrange(minMap,maxMap + 1/1):
        Configuration.set("game_creation", "map_x", i)
        Configuration.set("game_creation", "map_y", i)
        Configuration.removeAutoSave() #It need to remove all the autosave
        #modify the configuration file of openttd.cfg [difficulty] ->max_no_competitors -> i
        
        print "turn %d"%turn, "MapSize %d"%math.pow(2,i)
        print >> file, "-----------" + time.asctime() + "-----------\n" + "%f"%time.time()
        print >>file , "MapSize " + "%d"%i
    #   we need to use the cygwin to run the openttd, damn. In windows 7 cmd, there are some ini errors
    #   but when we are using the cygwin, there are also errors, so the error is bring about by the ini function    
        if sys.platform == "win32":
            os.system("cygwin.bat") 
        else :
            os.system("~/software/openttd-1.0.4/bin/openttd -g&")
        """
        we need to edit the autoexec.scr under the binary folder, to let it start_ai
        """
        #this call is a block, so i change the script call by cygwin to be background mode
        Process.killOpenTTD()
        print >> file,"%f"%time.time() + "\n-----------" + time.asctime() + "-----------\n"
        file.flush()
measurement.flag = 0

